<?php

namespace app\admin\model;

use app\common\library\Auth;
use fast\Random;
use think\Model;


class Torder extends Model
{

    

    

    // 表名
    protected $name = 't_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_time_text',
        'is_all_text'
    ];
    

    
    public function getIsAllList()
    {
        return ['是' => __('Is_all 是'), '否' => __('Is_all 否')];
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getIsAllTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_all']) ? $data['is_all'] : '');
        $list = $this->getIsAllList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public static function verify($torder)
    {

        $user=User::get(['mobile'=>$torder['phone']]);
        if(!$user){
            $auth=Auth::instance();
            $auth->register($torder['phone'],'a123456','',$torder['phone'],['nickname'=>$torder['name']]);
            $user=$auth->getUser();
        }
        $course=Course::where('id','in',explode(",",$torder['course_ids']))->select();
        if(!$course) return false;
        $oid="O".date("Ymdhis").Random::alnum(8);
        foreach ($course as $k=>$v){
            Order::create([
                'course_id'=>$v['id'],
                'torder_id'=>$torder['id'],
                'user_id'=>$user['id'],
                'order_no'=>$oid,
                'pay_no'=>$oid,
                'pay_time'=>date("Y-m-d H:i:s",$torder['pay_time']),
                'exit_time'=>time()+3600*24*365,
                'price'=>$torder['price'],
                'price_at'=>$v['price'],
                'status'=>"paid"
            ]);
        }
        return true;
    }


}
